package util;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletUtil extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4973977079335502422L;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url = req.getRequestURI();
		String result;
		int actionL = url.lastIndexOf("/");
		if (actionL > -1) {
			String actionS = url.substring(actionL + 1, url.length());
			int methodL = actionS.lastIndexOf("_");
			Class cls = null;
			String actionName;
			String methodName;
			if (methodL > -1) {
				actionName = actionS.substring(0, methodL);
				methodName = actionS.substring(methodL + 1, actionS.length());
			} else {
				actionName = actionS;
				methodName = "do";
			}
			try {
				Class[] parameterTypes = null;
				parameterTypes = new Class[] { HttpServletRequest.class };
				cls = Class.forName("zookeeper." + actionName);
				Method method = null;
				method = cls.getMethod(methodName, parameterTypes);
				result = (String) method.invoke(null, new Object[] { req });
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result="error";
			}
			resp.setContentType("text/html");
			resp.setCharacterEncoding("utf-8");
			PrintWriter pw = resp.getWriter();
			pw.write(result);
			pw.flush();pw.close();

		}

	}

}
